import {isEmpty,encrypt,judgeExpireTimestamp,UniAsync,callbackSugar} from './index'
import application from '@/settings/Application'

let {routeState} = application;

export function refreshForlogin(context) {
    // if (context.isLastPage()){
    //     uni.reLaunch({
    //         url: '/pages/tabbar/home/index'
    //     });
    //     return;
    // }
    // uni.navigateBack();
    //reLaunch

    // #ifdef H5
      uni.switchTab({
        url: '/pages/tabbar/home/index'
      });
  // #endif
    // #ifndef H5
    uni.reLaunch({
        url: '/pages/tabbar/home/index'
    });
    // #endif


    // const prePage = context.prePage();
    // const {path,meta} = prePage.__page__;
    // const {isTabBar} = meta;
    // if(isTabBar){
    //     uni.switchTab({
    //         url:path
    //     });
    //     return;
    // }
    // uni.redirectTo({
    //     url:path
    // });
    // return;
    // uni.navigateBack({
    //     success:function () {
    //         const prePage = context.prePage()
    //         prePage.onLoad();
    //       }
    // });
}

export function authCheck({exceptionCallback,callbackSuccess}){
    const tokenInfo = uni.getStorageSync('tokenInfo');
    const {token,timestamp} = tokenInfo
      if(isEmpty(tokenInfo) || isEmpty(token) || judgeExpireTimestamp(timestamp)) {
        uni.removeStorageSync('tokenInfo');
          if (exceptionCallback!=undefined && typeof exceptionCallback == 'function'){
            exceptionCallback();
          }else{
            uni.navigateTo({
                url: '/pages/system/login/index'
            })
          }
      }else{
          return callbackSugar(callbackSuccess,{token});
      }
}

export function routeForNotification(payload){
  const {notificationType='internal',source='',type,route,params} = payload;
  if(notificationType=='internal' && source!='click'){
    /*
    设置tabbar页消息红心badge
    */
    uni.$emit('onUpdateBadge',{value:'1'});  
    return;
  }
  if(type=='h5'){
    // uni.navigateTo({
    //   url: '/pages/web/web?src='+payload.url
    // });
  }else if(type=='internalroute'){
    uni.navigateTo({
      url: route
    });
  }
}


export function forwardLogin(){
  routeState.navigateToLogin = true;
   // #ifdef H5
      uni.navigateTo({
        url: '/pages/system/login/index'
      });
    // #endif
    // #ifndef H5
    uni.reLaunch({
        url: '/pages/system/login/index'
    });
  // #endif
}

//退出app
export function quitApp(){
	// #ifdef APP-PLUS  
	const platform =  uni.getSystemInfoSync().platform;
	switch(platform){
		case 'android':
		   plus.runtime.quit();
		   break;
		case 'ios':
		   const threadClass = plus.ios.importClass("NSThread");
		   const mainThread = plus.ios.invoke(threadClass, "mainThread");
		   plus.ios.invoke(mainThread, "exit");
		   break;
	}
	// #endif	
}